<?php
class My_Upload
{
	static private $_config = null;
	
	public static function init()
	{
		if(self::$_config == null) {
			self::$_config = My_Globals::getConfiguration();
		}
	}
	
	public static function upload($field, $time = null)
	{
		self::init();
		if($time == null) $time = time();
		$uploader = new Zend_File_Transfer_Adapter_Http();
		$fileInfo = $uploader->getFileInfo();
		$fileName = self::cleanName($fileInfo[$field]['name']);
		$uploader->addValidator('MimeType', false, explode(";", self::$_config->site->upload->mime_types));		
		$path = self::makeDirectory($time);
		if($path && $fileName && $uploader->isValid()) {
			try {
				$uploader->setDestination($path);
				$renameFilter = new Zend_Filter_File_Rename($path);
				$renameFilter->addFile( array('source' => $fileInfo[$field]['tmp_name'], 'target' => $fileName, 'overwrite' => true ) );
				$uploader->addFilter($renameFilter);
				$uploader->receive();
				if($uploader->isUploaded($field)) {
					return $fileName;
				}
			} catch(Zend_File_Transfer_Exception $e) {
				return null;
			}
		}
		return null;
	}
	
	public static function makeDirectory($time)
	{
		self::init();
		$path = self::$_config->site->upload->dir;
		// Make path by time
		$year = date("Y", $time);
		$month = date("m", $time);
		
		if(!is_dir($path.'/'.$year)) {
			mkdir($path.'/'.$year);
		}
		if(!is_dir($path.'/'.$year.'/'.$month)) {
			mkdir($path.'/'.$year.'/'.$month);
		}
		if(is_dir($path.'/'.$year.'/'.$month)) {
			return $path.'/'.$year.'/'.$month;
		}
		return null;
	}
	
	public static function cleanName($fileName)
	{
		self::init();
		$tmp = explode(".", $fileName);
		if(count($tmp) > 1) {
			$ext = $tmp[count($tmp)-1];
			$fileName = str_replace('.'.$ext, '', $fileName);
			$fileName = My_Globals::aliasCreator($fileName);
			if(in_array($ext, explode(',', self::$_config->site->upload->file_extensions))) {
				return $fileName.'.'.$ext;
			} 
		}
		return false;
	}
}